import 'dart:io';

import 'package:bloctest/utils/Constants.dart';
import 'package:bloctest/utils/sp_utils.dart';
import 'package:dio/dio.dart';

class DioInterceptor extends Interceptor {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    // TODO: implement onRequest
    print("请求url:${options.uri}");
    print("请求参数:${options.queryParameters}");
    print("请求头:${options.headers}");
    print("请求数据:${options.data}");
    print("请求方式:${options.method}");
    SpUtils.getStringList(Constants().COOKIE_LIST).then((cookList) {
      if (cookList!.isNotEmpty) {
        options.headers[HttpHeaders.cookieHeader] = cookList;
        handler.next(options);
      }
    });

    super.onRequest(options, handler);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    // TODO: implement onResponse
    print("返回:${response.data}");
    if (response.requestOptions.path.contains("user/login")) {
      dynamic list = response.headers[HttpHeaders.setCookieHeader];
      List<String> cookList = [];
      if (list is List) {
        for (String? cookie in list) {
          cookList.add(cookie ?? "");
        }
      }
      SpUtils.setStringList(Constants().COOKIE_LIST, cookList);
    }

    super.onResponse(response, handler);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    // TODO: implement onError
    super.onError(err, handler);
  }
}
